package com.epam.edu.command;

import com.epam.edu.dao.DAOUser;
import com.epam.edu.db.ConnectionPool;
import com.epam.edu.entity.User;
import com.epam.edu.util.CryptoUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * User: Zhanna_Mukanova
 * Date: 10/7/13
 * Time: 2:56 PM
 * To change this template use File | Settings | File Templates.
 */
public class ChangePasswordCommand implements Command {
    @Override
    public String perform(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, NoSuchAlgorithmException {
        StringBuilder errorMessage = new StringBuilder();
        String d = request.getParameter("oldPassword");
        String oldPassword = CryptoUtils.SHA1(request.getParameter("oldPassword"));
        HttpSession session = request.getSession();
        ConnectionPool pool = null;
        Connection connection = null;
        try {
            ConnectionPool.init();
            pool = ConnectionPool.getInstance();
            connection = pool.takeConnection();
            User user = DAOUser.selectById(connection, (Integer) session.getAttribute("userId"));
            errorMessage.append((!user.getPassword().equals(oldPassword)) ? "You have entered the wrong password<br>" : "");
            String newPassword = request.getParameter("newPassword");
            String confirmPassword = request.getParameter("confirmNewPassword");
            errorMessage.append((!newPassword.equals(confirmPassword)) ? "Password and confirm password do not match" : "");
            if (errorMessage.length() == 0) {
                user.setPassword(CryptoUtils.SHA1(newPassword));
                DAOUser.update(connection, user);
            } else {
                request.setAttribute("errorMessage", errorMessage);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/WEB-INF/jsp/changePassword.jsp";
    }
}
